package booyah.web;

import booyah.application.User;
import booyah.service.EventService;
import booyah.service.UserService;
import booyah.validation.LoginValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/login")
public class LoginController {

    private UserService userService;

    private EventService eventService;

    @Autowired
    public LoginController(UserService userService, EventService eventService) {
        this.userService = userService;
        this.eventService = eventService;
    }

    @RequestMapping(method = RequestMethod.GET)                          
    public String login(Model model) {
        model.addAttribute("loginPerson", new User());
        return "login";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String login(@ModelAttribute("loginPerson") User user, BindingResult result, Model model, HttpSession session) {
        User validatedUser = LoginValidator.validate(user, userService, result);
        if (result.hasErrors()) {
            return null; // Default view
        } else {
            session.setAttribute("user", validatedUser);
            return "redirect:/controller/user/show?id="+validatedUser.getId();
        }
    }
}
